<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>轮训聊天室</title>
    <style>
        .message {
            width: 300px;
            height: 500px;
            border: 2px solid red;
        }
    </style>
</head>
<body>
<div class="message"></div>
<div>
    <input type="text" placeholder="请输入发送的内容" id="txt">
    <input type="button" value="发送" onclick="SendMessage();">
</div>

{# 简称jquery cdn #}
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    function SendMessage() {
        var text = $("#txt").val(); // 获取文本框输入的内容
        $.ajax({
            url: "/send/msg/",  //发送消息
            data: {
                text: text
            },
            type: "GET",
            success: function (res) {
                console.log(res)
            }

        })
    }

    //每2秒向后台发送请求获取数据展示在界面上
    var max_index = 0;  //全局变量。最新元素的下表，从后端传递过来
    setInterval(function () {
        $.ajax({
            url: "/get/msg/",
            type: "GET",
            data: {
                index: max_index
            },
            success: function (dataArray) {
                console.log(dataArray, 1111);
                max_index = dataArray.index;
                {#var data = JSON.parse(res);#}  //用JsonResponse传递过来的所以，不用在转成字典
                $.each(dataArray.data, function (index, item) {  //遍历
                    var tag = $("<div>");
                    tag.text(item); // <div>你好</div>
                    $(".message").append(tag)  // 将生成好的div标签，添加到.message的后面
                })
            }
        })
    }, 2000)
</script>
</body>
</html>